package org.rcgwt.client.util;

/**
 * A pattern builder object. It can recognize specials characters to integrate
 * them in a Regular Expression.
 * 
 * @author Elian ORIOU
 * 
 */

public class PatternBuilder {

	private static final String ARGUMENT_TAG = "%%";
	private static final String symbols = "\\.*+?|()[]{}-^";

	/**
	 * Encodes a list of parameters, to integrate them in a regular expression.
	 * 
	 * @param regex
	 *            The regular expression where inject parameters.
	 * @param param
	 *            The parameters list to inject in the regular expression
	 * @return The encoded regular expression
	 */

	public static String encode(String regex, String... param) {
		int i = 1;
		String s = regex;
		for (String pa : param) {
			String r = format(pa);
			s = s.replace(ARGUMENT_TAG + i, r);
			i++;
		}
		return s;
	}

	/**
	 * Format the parameter, if it is a special character that will be
	 * interpreted by the regular expression engine.
	 * 
	 * @param tta
	 *            The parameter to format
	 * @return The parameter formated
	 */

	private static String format(String tta) {
		boolean isFound = false;
		String t = "";
		for (int i = 0; i < tta.length(); i++) {
			char c = tta.charAt(i);
			if (symbols.indexOf(c) != -1) {
				isFound = true;
				t += compatibility(c);
			} else if (isFound == true) {
				t += c;
			}
		}
		if (isFound == true) {
			return t;
		}
		return tta;
	}

	/**
	 * Returns the parameter character with a regular expression compatibility
	 * operator.
	 * 
	 * @param c
	 *            The incompatible character
	 * @return The compatible character
	 */

	private static String compatibility(char c) {
		return "\\" + String.valueOf(c);
	}
}
